<template>
    <div>
        <h2>WebRTC Video Chat with Socket.io</h2>
        <video ref="localVideo" autoplay playsinline></video>
        <video ref="remoteVideo" autoplay playsinline></video>
        <button @click="startCall">Start Call</button>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { io } from 'socket.io-client';

const localVideo = ref(null);
const remoteVideo = ref(null);
let localStream;
let peerConnection;

// 创建 socket.io 客户端
const socket = io('http://localhost:8080');

// 配置 STUN 服务器
const config = {
    iceServers: []
};

// 监听 socket.io 消息
socket.on('offer', async (data) => {
    await peerConnection.setRemoteDescription(new RTCSessionDescription(data));
    const answer = await peerConnection.createAnswer();
    await peerConnection.setLocalDescription(answer);
    socket.emit('answer', peerConnection.localDescription);
});

socket.on('answer', async (data) => {
    await peerConnection.setRemoteDescription(new RTCSessionDescription(data));
});

/* socket.on('candidate', async (data) => {
    const candidate = new RTCIceCandidate(data);
    await peerConnection.addIceCandidate(candidate);
}); */

socket.on('candidate', async (data) => {
  if (data.candidate) {
    try {
      await peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
    } catch (error) {
      console.error('Error adding received ice candidate:', error);
    }
  }
});


// 获取本地媒体流并初始化 PeerConnection
const getLocalStream = async () => {
    try {
        localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
        if (localVideo.value) {
            localVideo.value.srcObject = localStream;
        }

        peerConnection = new RTCPeerConnection(config);

        // 将本地流添加到 PeerConnection
        localStream.getTracks().forEach((track) => {
            peerConnection.addTrack(track, localStream);
        });

        // 处理 ICE 候选者
        peerConnection.onicecandidate = (event) => {
            if (event.candidate) {
                socket.emit('candidate', {
                    type: 'candidate',
                    candidate: event.candidate
                });
            }
        };


        // 接收远端流
        peerConnection.ontrack = (event) => {
            if (remoteVideo.value) {
                remoteVideo.value.srcObject = event.streams[0];
            }
        };
    } catch (error) {
        console.error('Error accessing media devices:', error);
    }
};

// 发起呼叫
const startCall = async () => {
    const offer = await peerConnection.createOffer();
    await peerConnection.setLocalDescription(offer);
    socket.emit('offer', offer);
};

onMounted(() => {
    getLocalStream();
});
</script>

<style scoped>
video {
    width: 300px;
    margin: 10px;
}
</style>